<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="商户号" prop="merchantCode">
        <el-input
          v-model="queryParams.merchantCode"
          placeholder="请输入商户号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账单号" prop="billNo">
        <el-input
          v-model="queryParams.billNo"
          placeholder="请输入账单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="快麦编码" prop="kmStoreCode">
        <el-input
          v-model="queryParams.kmStoreCode"
          placeholder="请输入快麦店铺编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="财务编码" prop="finStoreCode">
        <el-input
          v-model="queryParams.finStoreCode"
          placeholder="请输入财务编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="财店名称" prop="finStoreName">
        <el-input
          v-model="queryParams.finStoreName"
          placeholder="请输入财务店铺名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺名称" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入店铺名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺简称" prop="storeAbbr">
        <el-input
          v-model="queryParams.storeAbbr"
          placeholder="请输入店铺简称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="事业部名称" prop="divName">
        <el-select v-model="queryParams.divName" @keyup.enter.native="handleQuery" placeholder="请选择事业部名称" style="width: 100%;">
          <el-option v-for="dict in dict.type.div_name" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="storeLeader">
        <el-select v-model="queryParams.storeLeader" @keyup.enter.native="handleQuery" filterable clearable placeholder="请选择负责人" style="width: 100%;">
          <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId">
            <span style="float: left; margin-right: 10px;">{{ item.nickName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.userCode }} | {{item.phoneNumber}}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属平台" prop="platName">
        <el-select v-model="queryParams.platName" @keyup.enter.native="handleQuery" placeholder="请选择所属平台" style="width: 100%;">
          <el-option v-for="dict in dict.type.plat_name" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="toolbar">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['business:storeMgmt:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:storeMgmt:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:storeMgmt:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          @click="handleExport"
          v-hasPermi="['business:storeMgmt:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-refresh"
          @click="handleRefreshCache"
          v-hasPermi="['business:storeMgmt:refreshCache']"
        >刷新缓存</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div ref="divTable" :style="'height:' + divHeight + 'px'">
      <el-table v-loading="loading" :data="storeMgmtList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" width="50">
          <template v-slot="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="商户号" align="center" prop="merchantCode" />
        <el-table-column label="账单号" align="center" prop="billNo" />
        <el-table-column label="快麦编码" align="center" prop="kmStoreCode" />
        <el-table-column label="财务编码" align="center" prop="finStoreCode" />
        <el-table-column label="财店名称" align="center" prop="finStoreName" />
        <el-table-column label="店铺名称" align="center" prop="storeName" />
        <el-table-column label="店铺简称" align="center" prop="storeAbbr" />
        <el-table-column label="事业部名称" align="center" prop="divName">
          <template v-slot="scope">
            <dict-tag :options="dict.type.div_name" :value="scope.row.divName"/>
          </template>
        </el-table-column>
        <el-table-column label="店铺类型" align="center" prop="storeType">
          <template v-slot="scope">
            <dict-tag :options="dict.type.store_type" :value="scope.row.storeType"/>
          </template>
        </el-table-column>
        <el-table-column label="负责人" align="center" prop="storeLeader" >
          <template v-slot="scope">
            <user-tag :value="scope.row.storeLeader" type="userId"/>
          </template>
        </el-table-column>
        <el-table-column label="所属平台" align="center" prop="platName">
          <template v-slot="scope">
            <dict-tag :options="dict.type.plat_name" :value="scope.row.platName"/>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="storeStatus" width="55">
          <template v-slot="scope">
            <dict-tag :options="dict.type.sys_status" :value="scope.row.storeStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['business:storeMgmt:edit']"
            >修改</el-button>
            <el-button
              type="text"
              :icon="scope.row.storeStatus === 'DELETED' ? 'el-icon-refresh-left' : 'el-icon-delete'"
              @click="handleChangeStatus(scope.row)"
              v-hasPermi="['business:storeMgmt:changeStatus']"
            >{{scope.row.storeStatus === 'DELETED' ? "恢复" : "删除" }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :pageRefs="this.$refs"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
      />
    </div>
    <!-- 添加或修改店铺管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商户号" prop="merchantCode">
              <el-input v-model="form.merchantCode" clearable placeholder="请输入商户号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账单号" prop="billNo">
              <el-input v-model="form.billNo" clearable placeholder="请输入账单号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="快麦编码" prop="kmStoreCode">
              <el-input v-model="form.kmStoreCode" clearable placeholder="请输入快麦店铺编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="财务编码" prop="finStoreCode">
              <el-input v-model="form.finStoreCode" clearable placeholder="请输入财务店铺编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="财店名称" prop="finStoreName">
              <el-input v-model="form.finStoreName" clearable placeholder="请输入财店名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="店铺名称" prop="storeName">
              <el-input v-model="form.storeName" clearable placeholder="请输入店铺名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="店铺简称" prop="storeAbbr">
              <el-input v-model="form.storeAbbr" clearable placeholder="请输入店铺简称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事业部" prop="divName">
              <el-select v-model="form.divName" clearable placeholder="请选择事业部名称" style="width: 100%;">
                <el-option v-for="dict in dict.type.div_name" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="店铺类型" prop="storeType">
              <el-select v-model="form.storeType" clearable placeholder="请选择店铺类型" style="width: 100%;">
                <el-option v-for="dict in dict.type.store_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="storeLeader">
              <el-select v-model="form.storeLeader" filterable clearable placeholder="请选择店铺负责人" style="width: 100%;">
                <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId">
                  <span style="float: left; margin-right: 10px;">{{ item.nickName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.userCode }} | {{item.phoneNumber}}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="平台" prop="platName">
              <el-select v-model="form.platName" clearable placeholder="请选择所属平台" style="width: 100%;">
                <el-option v-for="dict in dict.type.plat_name" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" clearable type="textarea" :rows="2" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStoreMgmt, getStoreMgmt, addStoreMgmt, updateStoreMgmt, exportExcel, updateChangeStatus, refreshCache, getDoesItExist, delStoreMgmt } from "@/api/business/storeMgmt";
import { getNormalUserInfo} from "@/api/system/user";
import ResizeMixin from "@/layout/mixin/ResizeHandler";

export default {
  name: "StoreMgmt",
  mixins: [ResizeMixin],
  dicts: ['div_name', 'store_type', 'plat_name', 'sys_status'],
  data() {
    const validateReferenceLink = (rule, value, callback) => {
      this.checkReferenceLink(rule.field, value).then(res => {
        if (!res.isUnique) {
          callback(new Error(res.msg));
        } else {
          callback();
        }
      });
    };
    return {
      // div高度
      divHeight: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 店铺管理表格数据
      storeMgmtList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        merchantCode: null,
        billNo: null,
        kmStoreCode: null,
        finStoreCode: null,
        finStoreName: null,
        storeName: null,
        storeAbbr: null,
        divName: null,
        storeType: null,
        storeLeader: null,
        platName: null,
        storeStatus: null,
        userId: null,
        deptId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        merchantCode: [
          { required: true, message: '请输入商户编码', trigger: 'blur' },
          { validator: validateReferenceLink, trigger: 'blur' }
        ],
        billNo: [
          { required: true, message: '请输入账单号', trigger: 'blur' },
          { validator: validateReferenceLink, trigger: 'blur' }
        ],
        kmStoreCode: [
          { required: true, message: '请输入快麦编码', trigger: 'blur' },
          { validator: validateReferenceLink, trigger: 'blur' }
        ],
        finStoreCode: [
          { required: true, message: '请输入财务编码', trigger: 'blur' },
          { validator: validateReferenceLink, trigger: 'blur' }
        ],
        finStoreName: [
          { required: true, message: '请输入财务名称', trigger: 'blur' }
        ],
        storeAbbr: [
          { required: true, message: '请输入店铺简称', trigger: 'blur' },
          { validator: validateReferenceLink, trigger: 'blur' }
        ],
        storeName:[
          { required: true, message: '请输入店铺名称', trigger: 'blur' }
        ],
        divName:[
          { required: true, message: '请选择事业部', trigger: 'blur' }
        ],
        storeType:[
          { required: true, message: '请选择店铺类型', trigger: 'blur' }
        ],
        storeLeader:[
          { required: true, message: '请输入负责人名称', trigger: 'blur' }
        ],
        platName:[
          { required: true, message: '请选择平台', trigger: 'blur' }
        ]
      },
      // 用户集合
      userList: [],
    };
  },
  created() {
    this.getList();
    this.getUserList();
  },
  methods: {
    /** 获取用户集合 */
    getUserList(){
      getNormalUserInfo().then(response => {
        this.userList = response.data;
      });
    },
    checkReferenceLink(field, value) {
      let obj = {};
      obj[field] = value;
      obj.id = this.form.id;
      return new Promise(resolve => {
        if (value) {
          getDoesItExist(obj).then(response => {
            let msg = '';
            switch(field) {
              case 'merchantCode':
                msg = '商户编码不能重复';
                break;
              case 'billNo':
                msg = '账单号不能重复';
                break;
              case 'kmStoreCode':
                msg = '快麦编码不能重复';
                break;
              case 'finStoreCode':
                msg = '财务编码不能重复';
                break;
              case 'storeAbbr':
                msg = '店铺简称不能重复';
                break;
              default:
                msg = '字段不能重复';
            }
            resolve({
              isUnique: response.data.length === 0,
              msg: msg
            });
          });
        } else {
          resolve(true);
        }
      });
    },
    /** 查询店铺管理列表 */
    getList() {
      this.loading = true;
      listStoreMgmt(this.queryParams).then(response => {
        this.storeMgmtList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        merchantCode: null,
        billNo: null,
        kmStoreCode: null,
        finStoreCode: null,
        finStoreName: null,
        storeName: null,
        storeAbbr: null,
        divName: null,
        storeType: null,
        storeLeader: null,
        platName: null,
        storeStatus: null,
        userId: null,
        deptId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.$resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增店铺信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStoreMgmt(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改店铺信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStoreMgmt(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStoreMgmt(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('注意：此删除不可恢复，是否确认删除？').then(function() {
        return delStoreMgmt(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 删除或恢复按钮操作 */
    handleChangeStatus(row) {
      const ids = row.id || this.ids;
      let status = row.storeStatus === 'NORMAL'? '删除' : '恢复';
      this.$modal.confirm('是否确认' + status + '此数据项？').then(function() {
        row.storeStatus = row.storeStatus === 'NORMAL'? 'DELETED' : 'NORMAL';
        return updateChangeStatus(ids, row.storeStatus)
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(status + "成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      exportExcel(this.queryParams)
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache(){
      refreshCache().then(() => {
        this.$modal.msgSuccess("刷新成功");
      });
    }
  }
};
</script>
